package com.ctcemti.mdm.project.sys.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.ctcemti.mdm.common.result.Result;
import com.ctcemti.mdm.common.result.ResultEnum;
import com.ctcemti.mdm.common.result.ResultUtil;
import com.ctcemti.mdm.common.util.*;
import com.ctcemti.mdm.project.common.excelverifyhandler.ExcelVerifyHandlerForOrgJob;
import com.ctcemti.mdm.project.sys.dao.InfDictItemMapper;
import com.ctcemti.mdm.project.sys.dao.JobMapper;
import com.ctcemti.mdm.project.sys.entity.InfDictItem;
import com.ctcemti.mdm.project.sys.entity.OrgJob;
import com.ctcemti.mdm.project.sys.service.IJobService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class JobService implements IJobService {

    @Value("${ctcemti.errorfilepath}")
    private String errorfilepath;

    @Autowired
    InfDictItemMapper infDictItemMapper;

    @Autowired
    JobMapper jobMapper;

    @Override
    public Result insertOrUpdate(OrgJob orgJob) {
        if(orgJob == null){
            //
        }
        //判断编号是否重复
        if(!StringUtils.isNullOrEmpty(orgJob.getCode())){
            OrgJob temp = new OrgJob();
            temp.setName(orgJob.getCode().trim());

            if(jobMapper.selectCount(temp)>1){
                return ResultUtil.error(ResultEnum.ZTSJ_1005);
            }
            //判断是否是修改时没有修改名字
            if(jobMapper.selectCount(temp)==1){
                OrgJob org = jobMapper.selectOne(temp);
                if(!org.getId().equals(orgJob.getId())){
                    return ResultUtil.error(ResultEnum.ZTSJ_1005);
                }
            }
        }else{
            return ResultUtil.error(ResultEnum.ZTSJ_1001);
        }
        if(orgJob.getId() == null){
            orgJob.setId(UUID.randomUUID().toString());
            jobMapper.insert(orgJob);
        }else{
            jobMapper.updateByPrimaryKey(orgJob);
        }
        return ResultUtil.success();
    }

    @Override
    public Result importOrgs(List<OrgJob> jobs) {
        return null;
    }

    @Override
    public Result delete(String idStr) {
        if(StringUtils.isNullOrEmpty(idStr)){
            return ResultUtil.error(ResultEnum.ZTSJ_1001);
        }
        String[] ids = idStr.split(",");
        for(String id:ids){
            OrgJob orgJob = new OrgJob();
            orgJob.setId(id);
            jobMapper.delete(orgJob);
        }

        return ResultUtil.success();
    }

    @Override
    public PageInfo<OrgJob> getOrgJob(Map<String, Object> param) {
        Integer page = param.get("page")!=null&&!param.get("page").equals("")?Integer.parseInt(param.get("page").toString()):1;
        Integer limit = param.get("limit")!=null&&!param.get("limit").equals("")?Integer.parseInt(param.get("limit").toString()):1;
        Integer job = param.get("job")!=null&&!param.get("job").equals("")?Integer.parseInt(param.get("job").toString()):0;
        PageHelper.startPage(page,limit);
        PageHelper.orderBy("a.id");
        List<OrgJob> jobs = jobMapper.getJobs(job);
        PageInfo<OrgJob> pageJob = new PageInfo<>(jobs);
        return pageJob;
    }

    @Override
    public List<OrgJob> getJobByCode(String code) {
        Example example = new Example(OrgJob.class);
        Example.Criteria criteria =  example.createCriteria();
        criteria.andEqualTo("code",code);
        return jobMapper.selectByExample(example);
    }

    @Transactional
    @Override
    public Map<String, Object> uploadFile(MultipartFile multipartFile, HttpServletResponse response, HttpServletRequest request) throws IOException {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        List<InfDictItem> infDictItemList = infDictItemMapper.selectInfdictitemByInfdictsortCode("OrgJob");
        String loginId = JWTUtil.getLoginId(request.getHeader("Authorization"));
        ExcelImportResult<OrgJob> excelImportResult = ExcelParseUtils.importExcelMore(multipartFile,0,1,OrgJob.class,new ExcelVerifyHandlerForOrgJob(jobMapper,loginId,infDictItemList));
        boolean flag = true;
        if(excelImportResult == null){
            resultMap.put("flag",flag);
        }else if(excelImportResult.getFailList().size()>0){//验证失败，重新写入excel，并保存
            String filename = UUID.randomUUID().toString();//获取新的文件名
            File folder = new File(errorfilepath);//文件夹
            if(!folder.exists()){
                boolean mkFlag = folder.mkdirs();
                if (mkFlag) {
                    log.error("未找到上传文件夹，新建文件夹");
                }
            }
            FileOutputStream fos = null;
            try {
                //fileOutputStream = new FileOutputStream(file);
                //excelImportResult.getWorkbook().write(fileOutputStream);
                List<OrgJob> slist = excelImportResult.getList();//获取所有成功项
                List<OrgJob> flist = excelImportResult.getFailList();//获取所有失败项
                slist.addAll(flist);
                Collections.sort(slist);
                ExportParams exportParams = new ExportParams(null,null,"错误列表");
                exportParams.setStyle(ExcelExportStylerImpl.class);
                Workbook workbook = ExcelExportUtil.exportExcel(exportParams,OrgJob.class, slist);
                fos = new FileOutputStream(errorfilepath+"/"+filename+".xls");
                workbook.write(fos);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(fos!=null){
                    fos.close();
                }
            }
            flag = false;
            resultMap.put("flag",flag);
            resultMap.put("filecode",filename);
        }else{//成功验证，准备导入数据
            List<OrgJob> list = excelImportResult.getList();
            //物资字典库批量插入
            BatchOperationUtils<OrgJob> batchOperationUtils = new BatchOperationUtils();
            batchOperationUtils.batchOperation(list, 200,var->jobMapper.insertBatch(var));

            resultMap.put("flag",flag);
        }
        return resultMap;
    }

}
